package com.financing.wap.web.controller.api;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.ProductAttachmentDTO;
import com.financing.wap.service.IProductService;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.web.controller.BaseController;

/**
 * 文件下载controller
 * @author jtl
 *
 */
@Controller("apiFileController")
@RequestMapping("/api/file")
public class FileDownloadController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IProductService productService;
	
	@Autowired
	private MailSenderService mailSenderService;

	private String ctxPath = PropertiesUtils.getValue("ctxPath");
	
	/**
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downApp")
	public String downApp(HttpServletRequest request, HttpServletResponse response)  
			throws Exception {
		
		logger.info("===downAppUrl===>"+"");
		return "redirect:http://m.jincs.cn/jincs-SFA-release_v1.0.apk";
	}

	/**
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download")
	public String downloadFile(HttpServletRequest request, HttpServletResponse response,ProductAttachmentDTO attachment)  
			throws Exception {  

		List<ProductAttachmentDTO> attachments = productService.getProductAttachments(attachment);
		attachment = attachments.get(0);
		String fpath = attachment.getfPath();
		String fileName = fpath.substring(fpath.lastIndexOf("/") + 1);
		fpath =  fpath.substring(0,fpath.lastIndexOf("/")+1);

		String downLoadPath = ctxPath + fpath+URLEncoder.encode(fileName,"utf-8");
		downLoadPath = downLoadPath.replace("+", "");
		logger.info("===downLoadUrl===>"+downLoadPath);
		return "redirect:"+ downLoadPath;
	}  


	/**
	 * 下载文件发送至mail
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fileSendMail")
	@ResponseBody
	public ResultMap downloadFileByMail(HttpServletRequest request, HttpServletResponse response,ProductAttachmentDTO attachment,String emailAddress)  
			throws Exception {  
		ResultMap result = new ResultMap();
		List<ProductAttachmentDTO> attachments = productService.getProductAttachments(attachment);
		attachment = attachments.get(0);
		String fpath = attachment.getfPath();
		String fileName = fpath.substring(fpath.lastIndexOf("/") + 1);
		fpath =  fpath.substring(0,fpath.lastIndexOf("/")+1);

		String downLoadPath = ctxPath + fpath+URLEncoder.encode(fileName,"utf-8");
		String context="";
		logger.info("===downLoadUrl===>"+downLoadPath);
		
		MailContentDTO  mail = new MailContentDTO();
		mail.setSubject("subject");
		mail.setContext(context);
		mail.setRequestTime(new Date());
		mail.setRecAddress(emailAddress);
		mailSenderService.send(mail);
		return result;
	}
	
	/**
	 * 下载
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download2")
	@ResponseBody
	public ResultMap download(HttpServletRequest request, HttpServletResponse response,ProductAttachmentDTO attachment)  
			throws Exception {  

		request.setCharacterEncoding("UTF-8");  
		response.setContentType("text/html;charset=utf-8");  
		response.setContentType("multipart/form-data");  
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;  
		ResultMap result = new ResultMap();
		try {  
			List<ProductAttachmentDTO> attachments = productService.getProductAttachments(attachment);
			if(attachments.size()<=0){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("下载文件不存在！");
				return result;
			}
			attachment = attachments.get(0);
			String sURL = ctxPath + attachment.getfPath(); 
			URL url = new URL(sURL);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();  
			String fileName = sURL.substring(sURL.lastIndexOf("/") + 1);
			logger.info("文件下载全路径..."+sURL);  
			//获得文件长度  
			long nEndPos =getFileSize(sURL);  
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="  
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
			response.setHeader("Content-Length", String.valueOf(nEndPos));  
			bis = new BufferedInputStream(httpConnection.getInputStream());  
			bos = new BufferedOutputStream(response.getOutputStream());  
			byte[] buff = new byte[2048];  
			int bytesRead;  
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (bis != null)  
				bis.close();  
			if (bos != null)  
				bos.close();  
		}  
		return null;  
	}  

	//  获得文件长度  
	private  long getFileSize(String sURL) {  
		int nFileLength = -1;  
		try {  
			URL url = new URL(sURL);  
			HttpURLConnection httpConnection = (HttpURLConnection) url  
					.openConnection();  
			httpConnection.setRequestProperty("User-Agent", "Internet Explorer");  

			int responseCode = httpConnection.getResponseCode();  
			if (responseCode >= 400) {  
				logger.error("Error Code : " + responseCode);  
				return -2; // -2 represent access is error  
			}  
			String sHeader;  
			for (int i = 1;; i++) {  
				sHeader = httpConnection.getHeaderFieldKey(i);  
				if (sHeader != null) {  
					if (sHeader.equals("Content-Length")) {  
						nFileLength = Integer.parseInt(httpConnection  
								.getHeaderField(sHeader));  
						break;  
					}  
				} else  
					break;  
			}  
		} catch (IOException e) {  
			e.printStackTrace();  
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
		logger.info(nFileLength);
		return nFileLength;  
	}  

	public static void main(String[] orgs){
		String cc = "14146051216221028晚 安全报告.pdf";
		//		String xx = "14146051216221028%CD%ED+%B0%B2%C8%AB%B1%A8%B8%E6.pdf";
		String xx ="14146051216221028%E6%99%9A %E5%AE%89%E5%85%A8%E6%8A%A5%E5%91%8A.pdf";
		String n;
		try {
			n = URLEncoder.encode(cc,"utf-8");
			System.out.println(n);
			String n2 = URLDecoder.decode(xx,"utf-8");
			System.out.println(n2);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}  


